﻿using BlogTruyen.Models;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BlogTruyen.ViewModels
{
    public class Genre : Models.BaseModel
    {
        public ObservableCollection<Story> items { get; set; }
        public bool isLoaded { get; private set; }
        public string nextPage { get; private set; }
        public Genre()
        {
            items = new ObservableCollection<Story>();
            nextPage = "1";
        }
        public void LoadHtml(string html){
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            var sections = doc.DocumentNode.SelectNodes("//div[@class='hidden tiptip-content']");
            var pNodes = doc.DocumentNode.SelectSingleNode("//div[@class='list']").SelectNodes("./p[@class='']");
            HtmlNode titleNode,summaryNode,imgNode;
            int i=0;
            foreach (HtmlNode section in sections)
            {
                titleNode = section.SelectSingleNode("./div[@class='bold al-c fs-12']");
                summaryNode = section.SelectSingleNode("./div[@class='al-j fs-12']");
                imgNode = section.SelectSingleNode("./img");
                items.Add(new Story
                {
                    chapter_count=pNodes[i].SelectNodes("./span[@class='fs-12']")[2].InnerText.Trim(),
                    title = HttpUtility.HtmlDecode(titleNode.InnerText).Trim(),
                    summary = HttpUtility.HtmlDecode(summaryNode.InnerText).Trim(),
                    cover_img = imgNode.GetAttributeValue("src",""),
                    url=pNodes[i].SelectSingleNode(".//a").GetAttributeValue("href",""),
                });
                i++;
            }

            //next page
            nextPage = null;
            var pagingHome = doc.DocumentNode.SelectSingleNode("//div[@class='paging']");
            if (pagingHome != null)
            {
                var currentPage = pagingHome.SelectSingleNode("./span[@class='current_page']");
                var pageNodes = pagingHome.SelectNodes("./span");
                var currentPageIndex = pageNodes.IndexOf(currentPage);

                if (currentPageIndex < pageNodes.Count - 1)
                {
                    nextPage = pageNodes[currentPageIndex + 1].SelectSingleNode("./a").InnerText.Trim();
                }
            }
            isLoaded = true;
        }
    }
}
